package vista;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import modelo.tabla.ModeloTablaDatos;

/**
 *
 * @author Marlon
 */
public class FrmParamLibres extends javax.swing.JDialog {

    private List<Double> listPesos;
    private String[] nombres;
    private double bias;

    /** Creates new form FrmParamLibres */
    public FrmParamLibres(java.awt.Frame parent, boolean modal, int cantidadEntradas,
            double[][] mPesos) {
        super(parent, modal);

        listPesos = new ArrayList<Double>(cantidadEntradas + 1);
        bias = mPesos[0][0];
        nombres = new String[cantidadEntradas];

        for (int i = 0; i < cantidadEntradas; i++) {
            listPesos.add(mPesos[0][i + 1]);
            nombres[i] = "Peso " + (i + 1);
        }



        initComponents();
        initSpinners();

        spnrBias.setValue(bias);
        this.setLocationRelativeTo(null);
        //initTable();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tbarEjemplos = new javax.swing.JToolBar();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnGuardar = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        btnSalir = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        scrollPane = new javax.swing.JScrollPane();
        tableMPesos = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        spnrBias = new javax.swing.JSpinner();

        setTitle("Parámetros Libres");
        setResizable(false);

        tbarEjemplos.setBackground(new java.awt.Color(246, 246, 246));
        tbarEjemplos.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        tbarEjemplos.setFloatable(false);
        tbarEjemplos.setRollover(true);
        tbarEjemplos.setPreferredSize(new java.awt.Dimension(100, 31));

        jSeparator1.setForeground(new java.awt.Color(246, 246, 246));
        jSeparator1.setEnabled(false);
        jSeparator1.setOpaque(true);
        jSeparator1.setSeparatorSize(new java.awt.Dimension(270, 20));
        tbarEjemplos.add(jSeparator1);

        btnGuardar.setFont(new java.awt.Font("Segoe UI", 1, 11));
        btnGuardar.setText("Guardar");
        btnGuardar.setFocusable(false);
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGuardar.setMargin(new java.awt.Insets(3, 15, 3, 15));
        btnGuardar.setMaximumSize(new java.awt.Dimension(117, 27));
        btnGuardar.setMinimumSize(new java.awt.Dimension(117, 27));
        btnGuardar.setPreferredSize(new java.awt.Dimension(117, 27));
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        tbarEjemplos.add(btnGuardar);

        jSeparator2.setEnabled(false);
        jSeparator2.setSeparatorSize(new java.awt.Dimension(10, 25));
        tbarEjemplos.add(jSeparator2);

        btnSalir.setFont(new java.awt.Font("Segoe UI", 1, 11));
        btnSalir.setText("Salir");
        btnSalir.setFocusable(false);
        btnSalir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSalir.setMargin(new java.awt.Insets(3, 14, 3, 14));
        btnSalir.setMaximumSize(new java.awt.Dimension(117, 27));
        btnSalir.setMinimumSize(new java.awt.Dimension(117, 27));
        btnSalir.setPreferredSize(new java.awt.Dimension(117, 27));
        btnSalir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });
        tbarEjemplos.add(btnSalir);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel1.setText("Matriz de Pesos: ");

        tableMPesos.setModel(new ModeloTablaDatos(nombres, listPesos));
        tableMPesos.setFillsViewportHeight(true);
        scrollPane.setViewportView(tableMPesos);

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel2.setText("Bias:");

        spnrBias.setFont(new java.awt.Font("Tahoma", 0, 12));
        spnrBias.setModel(new javax.swing.SpinnerNumberModel(Double.valueOf(0.0d), Double.valueOf(0.0d), null, Double.valueOf(0.10000002384185791d)));
        spnrBias.setEditor(new javax.swing.JSpinner.NumberEditor(spnrBias, ""));
        spnrBias.setPreferredSize(new java.awt.Dimension(49, 30));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tbarEjemplos, javax.swing.GroupLayout.DEFAULT_SIZE, 518, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(spnrBias, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tbarEjemplos, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(40, 40, 40)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(46, 46, 46)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(spnrBias, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

        private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
            this.setVisible(false);
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        List<Double> data = ((ModeloTablaDatos) tableMPesos.getModel()).getData();
        System.out.println("VALORES ANTES");
        mostrarLista(data);
        mostrarLista(listPesos);
        bias = (Double) spnrBias.getValue();
        listPesos = data;
        System.out.println("VALORES DESPUES");
        mostrarLista(listPesos);


    }//GEN-LAST:event_btnGuardarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmParamLibres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmParamLibres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmParamLibres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmParamLibres.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
        
        @Override
        public void run() {
        FrmParamLibres dialog = new FrmParamLibres(new javax.swing.JFrame(), true, 5,new double[1][6]);
        dialog.addWindowListener(new java.awt.event.WindowAdapter() {
        
        @Override
        public void windowClosing(java.awt.event.WindowEvent e) {
        System.exit(0);
        }
        });
        dialog.setVisible(true);
        }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JSpinner spnrBias;
    private javax.swing.JTable tableMPesos;
    private javax.swing.JToolBar tbarEjemplos;
    // End of variables declaration//GEN-END:variables

    private void initTable() {
        tableMPesos.setDragEnabled(false);
    }

    private void mostrarLista(List<?> listValores) {
        for (Object elemento : listValores) {
            System.out.print(elemento + "  ");
        }
        System.out.println("");
    }

    public double getBias() {
        return bias;
    }

    public List<Double> getListPesos() {
        return listPesos;
    }

    private void initSpinners() {
        initSpinner(spnrBias, "#########.###########");
    }

    private void initSpinner(JSpinner spnr, String pattern) {
        JSpinner.NumberEditor editor = (JSpinner.NumberEditor) spnr.getEditor();
        DecimalFormat format = editor.getFormat();
        DecimalFormatSymbols simbolo = new DecimalFormatSymbols();
        simbolo.setDecimalSeparator('.');
        format.setDecimalFormatSymbols(simbolo);
        format.applyPattern(pattern);
        format.setMinimumFractionDigits(1);

        JTextField txt = editor.getTextField();
        txt.addFocusListener(new FocusAdapter() {

            @Override
            public void focusGained(java.awt.event.FocusEvent evt) {
                spnrFocusGained(evt);
            }
        });
    }

    private void spnrFocusGained(FocusEvent evt) {
        JTextField txt = (JTextField) evt.getSource();

        System.out.println("Estas en el spinner " + evt.getSource().getClass().getName());

        // Con esto me evito el problema de no seleccionar el Texto en la GUI
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4699955
        // ver ese enlace para solucionarlo. En la parte final se ve una recomendacion
        txt.setText(txt.getText());
        txt.selectAll();

        System.out.println(txt.getSelectedText());
    }
}
